# -*- coding: utf-8 -*-
"""
工单相关的 SQL 仓库
"""
from __future__ import annotations

from typing import Dict, Any, Optional
from common.database import DatabaseManager
from common.logger import create_logger

logger = create_logger(__name__)


class WorkOrderRepository:
	def __init__(self, db: DatabaseManager):
		self.db = db

	def find_work_order_by_alarm(self, alarm_id: int) -> Optional[Dict[str, Any]]:
		"""查找告警关联的工单（加锁）"""
		rows = self.db.execute_query(
			"""
			SELECT w.id, w.status
			FROM wo_work_order w
			JOIN am_alarm_work m ON m.work_order_id=w.id
			WHERE m.alarm_id=%s
			FOR UPDATE
			""",
			(alarm_id,),
			commit=False
		)
		return rows[0] if rows else None

	def find_open_work_order_by_alarm(self, alarm_id: int) -> Optional[Dict[str, Any]]:
		"""查找告警关联的未关闭工单（加锁）"""
		rows = self.db.execute_query(
			"""
			SELECT w.id
			FROM wo_work_order w
			JOIN am_alarm_work m ON m.work_order_id=w.id
			WHERE m.alarm_id=%s AND w.status NOT IN ('CLOSED', 'AUTO_CLOSED')
			FOR UPDATE
			""",
			(alarm_id,),
			commit=False
		)
		if rows:
			logger.info(f"找到告警 {alarm_id} 对应的工单: {rows[0]['id']}")
		return rows[0] if rows else None

	def auto_close_work_order(self, wo_id: int) -> None:
		"""系统自动关闭工单"""
		self.db.execute_query(
			"""
			UPDATE wo_work_order
			SET status='AUTO_CLOSED', closed_by='SYSTEM', closed_at=NOW(),
				close_comment='告警已恢复，系统自动关闭',
				solution='系统检测到告警恢复，自动关闭'
			WHERE id=%s
			""",
			(wo_id,),
			commit=False,
		)

	def insert_work_order_log(self, wo_id: int, comment: str) -> None:
		"""记录工单流转日志"""
		self.db.execute_query(
			"""
			INSERT INTO wo_work_order_log
			(wo_id, action, actor_code, actor_name, comment, old_status, new_status)
			VALUES (%s, 'AUTO_CLOSE', 'SYSTEM', '系统', %s, 'CREATED', 'AUTO_CLOSED')
			""",
			(wo_id, comment),
			commit=False,
		)

	def insert_work_order(self, code: str, title: str, alarm_id: int, description: str) -> int:
		"""插入新工单"""
		sql = """
            INSERT INTO wo_work_order
              (code, title, source_type, alarm_id, priority, description, expect_finish_time, status, created_at)
            VALUES (%s,%s,'ALARM',%s,'HIGH',%s,DATE_ADD(NOW(), INTERVAL 2 HOUR),'CREATED',NOW())
            ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id)
        """
		self.db.execute_query(
			sql,
			(code, title, alarm_id, description),
			commit=False
		)
		return self.db.last_insert_id()